<?php
class Business_Product
{
	protected $_tableName = "product";

	public function getByCateId($cateId, $page = 1, $rowCount = 8)
	{
		$fields = array("id", "name", "cover");
		$select = Db_Factory::getInstance()->createSelect();
		$select->from($this->_tableName, $fields);
		$select->where('cateid = ?', $cateId);
		$select->limitPage($page, $rowCount);
		$stmt = $select->query();
		$result = $stmt->fetchAll();
		return $result;
	}
	
	/**
	 * 获得某分类下产品总数
	 * @param Integer $cateId
	 * @return Integer
	 */
	public function getByCateIdAmount($cateId)
	{
	    $select = Db_Factory::getInstance()->createSelect();
	    $select->from($this->_tableName, "count(*) as count")
	           ->where('cateid = ?', $cateId);
	    $stmt = $select->query();
	    $result = $stmt->fetch();
	    $count = isset($result['count']) ? $result['count'] : 0;
	    return $count; 
	}
	
	/**
	 * 根据ID获取产品
	 * @param Integer $id
	 * @return Array
	 */
	public function getById($id)
	{
	    $fields = array('id', 'name', 'cover', 'introduce', 'cateid', 'show_homepage');
	    $select = Db_Factory::getInstance()->createSelect();
	    $select->from($this->_tableName, $fields)
	            ->where("id = ?", $id);
	    return $select->query()->fetch();
	}
	
	/**
	 * 获取首页显示的产品
	 * @return array
	 */
	public function getHomePageProduct()
	{
	    $fields = array("id", "name", "cover");
	    $select = Db_Factory::getInstance()->createSelect();
	    $select->from($this->_tableName, $fields);
	    $select->where('show_homepage = ?', 1);
	    $stmt = $select->query();
	    $result = $stmt->fetchAll();
	    return $result;
	}
	
	public function add($data)
	{
		$data['ctime'] = $data['mtime'] = date("Y-m-d H:i:s");
		$table = Db_Factory::getInstance()->createTable($this->_tableName);
		return $table->insert($data);
	}
	
	public function update($data, $pid)
	{
		$data['mtime'] = date("Y-m-d H:i:s");
		$where = array("id = ?" => $pid);
		$table = Db_Factory::getInstance()->createTable($this->_tableName);
		return $table->update($data, $where);
	}
	
	public function delete($pid)
	{
		$cateId = intval($pid);
		$where = array("id = ?" => $pid);
		$table = Db_Factory::getInstance()->createTable($this->_tableName);
		return $table->delete($where);
	}
}